<%--
  Created by IntelliJ IDEA.
  User: MI
  Date: 2023/3/17
  Time: 14:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<link rel="stylesheet" media="all" href="${pageContext.request.contextPath}/layui/css/layui.css">
<script src="${pageContext.request.contextPath}/layui/layui.js"></script>
<script src="${pageContext.request.contextPath}/layui/echarts.js"></script>
<script src="${pageContext.request.contextPath}/js/html2canvas.js"></script>
<script src="${pageContext.request.contextPath}/js/jspdf.debug.js"></script>

<%--<script src="${pageContext.request.contextPath}/js/jquery-3.6.1.js"></script>--%>
<html>
<head>
  <title>FPA测试结果页面</title>
</head>
<style>
  .main-div {
    width: 550px;
  }

  @media screen and (max-device-width: 1000px) {
    .main-div {
      width: 100%;
    }
  }
</style>
<body>

<script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-danger " lay-event="delete"><i class="layui-icon layui-icon-delete"></i>删除</a>
</script>

<script type="text/html" id="rowBarDemo">
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="check">查看</a>
</script>

<form class="layui-form" action="" style="margin-top: 10px">
  <div class="layui-inline">
    <label class="layui-form-label">姓名</label>
    <div class="layui-input-inline">
      <input type="text" name="name" placeholder="请输入姓名" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-inline">
    <label class="layui-form-label">测试计划ID</label>

    <div class="layui-inline" style="width: 235px;">
      <select placeholder="选择ID" id="cccc" name="test_plan_id"></select>
    </div>
  </div>
  <div class="layui-inline">
    <div class="layui-input-inline">
      <button class="layui-btn" lay-submit lay-filter="selectFormfilter">查询</button>
      <button type="reset" class="layui-btn layui-btn-primary" id="myButton">重置</button>
    </div>
  </div>
</form>

<div id="show" style="width: 100%;height: 100%; display: none;">
  <fieldset class="layui-elem-field" id="ceshi">

    <!--startprint1-->
    <input id="character" value="黄" hidden>
    <div class="layui-row  " >
      <div class="layui-col-md7">
        <div class="main-div" id="myPdf" align="auto">
          <div style="background-color:#fcf4ed;border-radius:40px 40px 0 0;z-index: 2;padding: 40px 20px 20px 20px;color: #41464B">
            <h1 style="text-align:center;line-height: 60px;font-size: 30px;font-weight: 600;color: #7a2114;">
              测评报告预览</h1>
            <div style="background: rgba(87,144,255,.2);padding: 20px;text-align: center;margin-bottom: 20px"
                 id="div1">

            </div>
            <div id="shopping" style="width:100%;height:400px;"></div>

            <div style="background: rgba(87,144,255,.2);padding: 20px;margin-top: 20px;text-align: center"
                 id="div2">

            </div>
            <div style="background: white;padding: 20px;margin-top: 20px; text-align: center" id="div3">

            </div>
          </div>
        </div>
      </div>
    </div>
    <!--endprint1-->
  </fieldset>



  <div style="margin-left:40%;">
    <button class="layui-btn" target="_blank" rel="external nofollow" onclick="makeMpdf('Fpa检测报告')">下载Fpa检测文件
    </button>
  </div>

</div>

<table id="demo" lay-filter="test"></table>
</body>
<script>

  function makeMpdf(pdfName) {
    if (confirm("您确认下载该PDF文件吗?")) {
      $("#ceshi").css('background-color', '#FFF');
      var element = $("#ceshi"); // 这个dom元素是要导出pdf的范围div
      var w = element.width();    // 获得该容器的宽
      var h = element.height();    // 获得该容器的高
      var offsetTop = element.offset().top;    // 获得该容器到文档顶部的距离
      var offsetLeft = element.offset().left;    // 获得该容器到文档最左的距离
      var canvas = document.createElement("canvas");
      var abs = 0;
      var win_i = $(window).width();    // 获得当前可视窗口的宽度（不包含滚动条）
      var win_o = window.innerWidth;    // 获得当前窗口的宽度（包含滚动条）
      if(win_o>win_i){
        abs = (win_o - win_i)/2;    // 获得滚动条长度的一半
      }
      canvas.width = w;    // 将画布宽&&高放大4倍
      canvas.height = h;
      var context = canvas.getContext("2d");
      context.scale(1, 1);
      context.translate(-offsetLeft-abs,-offsetTop);
      //这里默认横向没有滚动条的情况，因为offset.left(),有无滚动条的时候存在差值，因此translate的时候，要把这个差值去掉
      html2canvas(element, {
        allowTaint: true,
        taintTest: true,
        canvas: canvas,
        // dpi: 172,//导出pdf清晰度
        onrendered: function(canvas) {
          var contentWidth = canvas.width;
          var contentHeight = canvas.height;
          //一页pdf显示html页面生成的canvas高度;
          var pageHeight = contentWidth;
          //未生成pdf的html页面高度
          var leftHeight = contentHeight;
          //页面偏移
          var position = 0;
          //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
          var imgWidth = 595.28;
          var imgHeight = 592.28/contentWidth * contentHeight;
          var pageData = canvas.toDataURL('image/jpeg', 1.0);
          var pdf = new jsPDF('', 'pt', [contentWidth, contentHeight]);
          //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
          //当内容未超过pdf一页显示的范围，无需分页
          // if (leftHeight < pageHeight) {
          pdf.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight);
          // } else {    // 分页
          //     while(leftHeight > 0) {
          //         pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
          //         leftHeight -= pageHeight;
          //         position -= 841.89;
          //         //避免添加空白页
          //         if(leftHeight > 0) {
          //             pdf.addPage();
          //         }
          //     }
          // }
          pdf.save(pdfName+'.pdf');
        }
      });
    }
  }

  layui.config({
    version: 1,
    base: '${pageContext.request.contextPath}/echarts/' //这个就是你放Echart.js的目录
  }).use(['table', 'jquery', 'form', 'laydate', 'echarts'], function () {
    var table = layui.table;
    var form = layui.form;
    var $ = layui.jquery, laydate = layui.laydate, echarts = layui.echarts;

    //第一个实例
    var myTable = table.render({
      elem: '#demo'
      , height: 550
      , url: 'http://localhost:8080/FirstPhase_war/result/findAllrt' //数据接口
/*      , parseData: function (res) { //res 即为原始返回的数据
        return {
          "code": 0, //解析接口状态
          "msg": "", //解析提示文本
          "count": res.totalElements, //解析数据长度
          "data": res.content //解析数据列表
        };
      }*/
      , page: true //开启分页
      , limit: 10
      , limits: [5, 10, 15, 20, 25, 30, 50, 100]
      , toolbar: '#barDemo'
      , cols: [
        [ //表头
          {type: 'checkbox', fixed: 'left'}
          , {field: 'tester_id', title: 'ID', width: 120, sort: true}
          , {field: 'name', title: '姓名', width: 120}
          , {field: 'phone', title: '电话', width: 120}
          , {field: 'create_time', title: '测试时间', width: 120}
          , {field: 'red_count', title: '红色得分', width: 120, sort: true}
          , {field: 'yellow_count', title: '黄色得分', width: 120, sort: true}
          , {field: 'blue_count', title: '蓝色得分', width: 120, sort: true}
          , {field: 'green_count', title: '绿色得分', width: 120, sort: true}
          , {field: 'test_plan_id', title: '测试计划ID', width: 120, sort: true}
          , {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#rowBarDemo'}
        ]
      ]
    });
    /*
    *
    * 行内工具栏
    * */
    //监听行工具事件
    table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
      var data = obj.data //获得当前行数据
              , layEvent = obj.event; //获得 lay-event 对应的值
      if (layEvent === 'check') {
        //layer.msg('查看操作');
        //弹出层
        layer.open({
          title: '性格测试结果图示',
          type: 1,
          content: $('#show'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
          area: ['571px', '700px']
        });
        $.ajax({
          url: "http://localhost:8080/FirstPhase_war/result/check",
          type: "POST",
          dataType: "JSON",
          data: {tester_id:data.tester_id},
          success: function (ret) {
            var red = ret.red_count
            var blue = ret.blue_count
            var yellow = ret.yellow_count
            var green = ret.green_count

            var myChart = echarts.init(document.getElementById('shopping'));
            var option = {
              title: {
                text: 'FPA性格测试',
                left: 'center'
              },
              tooltip: {
                trigger: 'item'
              },
              legend: {
                orient: 'vertical',
                left: 'left'
              },
              series: [
                {
                  name: 'Fpa性格占比',
                  type: 'pie',
                  radius: '70%',
                  data: [
                    {value: red, name: '红色性格', itemStyle: {color: '#c51313'}},
                    {value: blue, name: '蓝色性格', itemStyle: {color: '#1061ba'}},
                    {value: yellow, name: '黄色性格', itemStyle: {color: '#f8ff14'}},
                    {value: green, name: '绿色性格', itemStyle: {color: '#2dcc00'}},
                  ],
                  emphasis: {
                    itemStyle: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                  }
                }
              ]
            };

            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);


            var a = [blue, red, yellow, green];

            function f(a, b) {  //排序函数

              return (a - b);  //返回比较参数

            }

            a = a.sort(f)
            if (a[a.length - 1] == yellow) {
              color = 1
            } else if (a[a.length - 1] == red) {
              color = 2
            } else if (a[a.length - 1] == blue) {
              color = 3
            } else {
              color = 4
            }
            $.ajax({
              url: "http://localhost:8080/FirstPhase_war/result/checkdiv",
              type: "POST",
              dataType: "JSON",
              data: {id: color},
              success: function (ret) {
                $('#div1').html(ret.div1)
                $('#div2').html(ret.div2)
                $('#div3').html(ret.div3)
              }
            });

          }
        })
      }/* else if (obj.event === 'del') {
        layer.confirm('您真的删除行么', function (index) {
          // 删除用户信息
          $.ajax({
            url: '/springmvc/viewTestResultFpa/deleteResultFpa.do',
            type: 'POST',
            dataType: 'JSON',
            data: {testerId: data.testerId},
            success: function (data) {
              if (data.code == 0) {
                // 关闭对话框
                layer.closeAll();
                // 刷新表格数据
                table.reload('demo');
              }
              layer.msg(data.msg);
            }
          });
        });
      }*/
    })
    //监听头工具栏事件
    table.on('toolbar(test)', function (obj) {
      var checkStatus = table.checkStatus(obj.config.id)
              , data = checkStatus.data; //获取选中的数据
      switch (obj.event) {
        case 'delete':
          if (data.length === 0) {
            layer.msg('请选择一行');
          } else {
            layer.confirm('真的删除选中的行么', function (index) {
              //obj.del(); //删除对应行（tr）的DOM结构
              //删除数据库中的数据
              var idList = [];
              //遍历数组data，抽取所有的id
              for (let i = 0; i < data.length; i++) {
                idList[i] = (data[i].tester_id);
              }
              $.ajax({
                url: "${pageContext.request.contextPath}/result/deletesrt",
                type: "POST",
                dataType: "JSON",
                data: {tester_id: idList.join(",")},
                success: function (ret) {
                  if (ret >= 1) {
                    //刷新表格数据
                    myTable.reload({
                      page: {
                        curr: 1 //重新从第 1 页开始
                      }
                    });
                    layer.msg('成功', {icon: 6});
                  } else {
                    layer.msg('失败', {icon: 5});
                  }
                }
              })
              layer.close(index);
              //向服务端发送删除指令
            });
          }
          break;
      }
    })
    //====================================提交条件查询==================================================
    $.ajax({
      url: "${pageContext.request.contextPath}/result/findAllrt",
      type: "POST",
      dataType: "JSON",
      success: function (ret) {
        if (ret.code == 0) {
          //<option value="0">写作</option>
          var htmlStr = "<option value=''>请选择ID</option>";
          for (let i = 0; i < ret.data.length; i++) {
            htmlStr += "<option value=" + ret.data[i].testPlanId + ">测试ID：" + ret.data[i].testPlanId + "</option>"
          }
          // var htmlStr="<option value='男'>男</option>"
          // htmlStr=htmlStr+"<option value='女'>女</option>"
          $("#cccc").html(htmlStr);
          //重新渲染表单
          layui.use('form', function () {
            form.render('select');
          })
        }
      }
    });
    form.on('submit(selectFormfilter)', function (data) {
      //提交表单数据
      myTable.reload({
        where: { //设定异步数据接口的额外参数，任意设
          name: data.field.name,
          testPlanId: data.field.testPlanId
        }
        ,
        page: {
          curr: 1 //重新从第 1 页开始
        }
      });
      return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    ///重置条件查询表单，刷新table数据
    $("#myButton").click(function () {
      myTable.reload({
        where: { //设定异步数据接口的额外参数，任意设
          name: "",
          testPlanId: ""
          //…
        }
        , page: {
          curr: 1 //重新从第 1 页开始
        }
      });
    })
  })
</script>
</html>
